package controllers

import (
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"go.didapinche.com/foundation/plat-echo/app/ops/services"
	"go.didapinche.com/foundation/plat-echo/pkg/constants"
	"go.didapinche.com/time"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	time2 "time"
)

type AlertCurrentController struct {
	service services.AlertCurrentService
	logger  *zap.Logger
}

func NewAlertCurrentController(service services.AlertCurrentService, logger *zap.Logger) *AlertCurrentController {
	return &AlertCurrentController{
		service: service,
		logger:  logger.With(zap.String("type", "controller.alert_current")),
	}
}

func (ctl AlertCurrentController) FindAlerts(c *gin.Context) {
	param := new(struct {
		GroupID string    `form:"group_id"`
		Level   int       `form:"level"`
		Start   time.Time `form:"start"`
		Uid     string    `form:"uid"`
		End     time.Time `form:"end"`
	})
	err := c.BindQuery(param)
	if err != nil {
		ctl.logger.Error("bind json error", zap.Error(err))
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	if param.Start.Time.Year() < 2006 {
		param.Start.Time = time2.Now().AddDate(0, 0, -1)
		param.End.Time = time2.Now()
	}
	alerts, err := ctl.service.FindByGroupAndLevel(c.Request.Context(), param.GroupID, param.Uid, param.Level, param.Start, param.End)
	if err != nil {
		if errors.Is(err, context.Canceled) {
			ctl.logger.Error("context canceled", zap.Error(err))
			c.Status(constants.StatusRequestCanceled)
			return
		}
		ctl.logger.Error("call AlertCurrentService.FindByGroupAndLevel error", zap.Error(err))
		c.String(http.StatusInternalServerError, err.Error())
		return
	}
	c.JSON(http.StatusOK, alerts)
}

func (ctl AlertCurrentController) FindByAppID(c *gin.Context) {
	//start, err := time2.ParseInLocation("2006-01-02 15:04:05", c.Query("start"), time2.Local)
	//if err != nil {
	//	c.String(http.StatusBadRequest, "bind param error:%v", err)
	//	return
	//}
	//end, err := time2.ParseInLocation("2006-01-02 15:04:05", c.Query("end"), time2.Local)
	//if err != nil {
	//	c.String(http.StatusBadRequest, "bind param error:%v", err)
	//	return
	//}
	//if start.Year() < 2006 {
	//	start = time2.Now().AddDate(0, 0, -1)
	//	end = time2.Now()
	//}
	start := time2.Now().AddDate(0, 0, -1)
	end := time2.Now()
	appID := c.Param("id")
	AppID, err := strconv.ParseUint(appID, 10, 64)
	if err != nil {
		ctl.logger.Error("bind appID error", zap.Error(err))
		c.String(http.StatusBadRequest, err.Error())
		return
	}
	alerts, err := ctl.service.FindByAppID(c.Request.Context(), AppID, time.Time{start}, time.Time{end})
	if err != nil {
		if errors.Is(err, context.Canceled) {
			ctl.logger.Error("context canceled", zap.Error(err))
			c.Status(constants.StatusRequestCanceled)
			return
		}
		ctl.logger.Error("call AlertCurrentService FindByAppID error", zap.Error(err))
		c.String(http.StatusInternalServerError, err.Error())
		return
	}
	c.JSON(http.StatusOK, alerts)
}
